package com.rzjm.api.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  用户技能相关接口
 *@Date 2018-05-10
 */
@Component
@RequestMapping("/test")//url:模块/资源/{}/细分
public class TestController extends BaseController {

    @Resource
    private ShopService shopService;
    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private CkTerminalService ckTerminalService;
    @Resource
    private TerminalFittingService terminalFittingService;
    @Resource
    private TerminalCheckRecordService terminalCheckRecordService;
    @Resource
    private TerminalRecordRepairService terminalRecordRepairService;
    @Resource
    private TerminalCheckRecordImgService terminalCheckRecordImgService;
    @Resource
    private TerminalRecordRepairImgService recordRepairImgService;
    @Resource
    private SysErrorService sysErrorService;
    @Resource
    private UserShopRelationService userShopRelationService;
    @Resource
    private SysDictService sysDictService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private UserMpService userMpService;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    @Value("${web.appid_mp}")
    private String appidMp;//图片地址
    @Value("${web.secret_mp}")
    private String secretMp;//图片地址

    @Value("${web.imgprefix}")
    private String imgprefix;//图片地址

    /**
     * 添加终端设备巡查记录
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/test",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject test(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            Integer terminal_id = jsonRequest.containsKey("terminal_id") ? jsonRequest.getInt("terminal_id") : 0;
            Integer record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;
            User user = userService.findById(user_id);
//            if(user == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
//            }


            String token = "82_7VxP2HX9QLPXKD7H_iGZO2yPYONS8SeEofQ14vgGt5fSG7CCZc3MQOfl295X7-Qb0f1w5ZSKkGDrDNL4HryDQIWvE-Qezg2mGoo1irN6GjW-5kdTDDFfr4T5-owPSZjACAZCJ";
            WxMessage.resetTokenCount(appidMp, secretMp);

//            List<Map<String,Object>> fittings = terminalFittingService.getWarningPageByUserId(7);

//            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
//            if(sysUser == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
//            }
//
//            CkTerminal terminal = ckTerminalService.getById(terminal_id);
//            if(terminal == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该终端信息异常，请重试"),true,true);
//            }
//
//            CkTerminalCheckRecord record = terminalCheckRecordService.findById(record_id);
//
            System.out.println("开始发送消息");
//            sendWxMsg(terminal,record,3);//发送推送消息
//            System.out.println("结束发送消息");

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/addCheck",e);
        }
        return result;
    }


    private void sendWxMsg(CkTerminal terminal, TerminalCheckRecord record, Integer template_type){
        try{
            QueryWrapper<SysUser> qw = new QueryWrapper<>();
            qw.eq("user_id",3);

            String accessToken = wxTemplateService.getAccessToken(appidMp,secretMp, 1);
            List<SysUser> sysUsers = sysUserService.list(qw);
            if(sysUsers != null && sysUsers.size() > 0){
                for(SysUser sysUser : sysUsers){
                    List<User> users = userService.selectListByColumn("sys_user_id",sysUser.getUserId());
                    if(users != null){
                        for (User user :users){
                            if(user != null && sysUser.getIsSendMsg().intValue() == 1 && StrUtil.isNotEmpty(user.getUnionId())){
                                WxMsgTemplate template = null;
                                if(template_type == 1){//报修
                                    template = getTemplate(terminal,user,record.getCheckResult());
                                }else{//维修完成
                                    template = getRepairedTemplate(terminal,user,sysUser,record);
                                }
//                                System.out.println("模板消息：" + template.toString());
                                String param = net.sf.json.JSONObject.fromObject(template).toString();
                                JSONObject jsonObject = WxMessage.sendMsg(accessToken,param);
                                if(jsonObject != null){
                                    int errcode = jsonObject.getInt("errcode");
                                    System.out.println("jsonObject:" + jsonObject.toString());
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
    }

    private WxMsgTemplate getTemplate(CkTerminal terminal,User user,String check_result){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",1);
        UserMp userMp = userMpService.selectByUniqueColumn("unionid",user.getUnionId());
        if(userMp!=null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");
            Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();

            MsgTempData first = new MsgTempData();
            first.setColor("#173177");
            first.setValue("管理员您好，有设备出现报修警报");
            m.put("first",first);

            //设备名称
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(terminal.getTerminalName());
            m.put("keyword1",keyword1);

            //设备编号
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(terminal.getTerminalNum());
            m.put("keyword2",keyword2);

            //在线状态
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue("设备在线");
            m.put("keyword3",keyword3);

            //最后时间
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            keyword4.setValue(DateUtil.getTime());
            m.put("keyword4",keyword4);

            //设备状态
            MsgTempData keyword5 = new MsgTempData();
            keyword5.setColor(wxTemplate.getFontColor());
            keyword5.setValue("该设备存在异常报修，请及时处理");
            m.put("keyword5",keyword5);


            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue(check_result);
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    /**
     *  维修完成的推送消息
     * @param terminal
     * @param user
     * @param record
     * @return
     */
    private WxMsgTemplate getRepairedTemplate(CkTerminal terminal, User user, SysUser sysUser, TerminalCheckRecord record){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",3);
        UserMp userMp = userMpService.selectByUniqueColumn("unionid",user.getUnionId());
        if(userMp!=null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");
            template.setTopColor(wxTemplate.getFontColor());
            Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();

            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("管理员您好，" + terminal.getTerminalName()+ terminal.getTerminalNum() + "修复完毕通知");
            m.put("first",first);

            //维修人员
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(sysUser.getName());
            m.put("keyword1",keyword1);

            //联系电话
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(sysUser.getMobile());
            m.put("keyword2",keyword2);

            //完成时间
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(DateUtil.getTime());
            m.put("keyword3",keyword3);

            //报修原因
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            keyword4.setValue(record.getCheckResult());
            m.put("keyword4",keyword4);

            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getSpicalFontColor());
            remark.setValue(terminal.getTerminalName()+ terminal.getTerminalNum() + "修复完毕通知");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }
}
